/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "tim.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "lcd.h"
#include "stdio.h"
#include "string.h"
#include "key.h"
#include "math.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
//显示界面
#define DATA 0
#define PARA 1
#define RECD 2
uint8_t LCD_Display;
//显示参数
_Bool PWM_mode;		//0低速  1高速
uint8_t Pulse;
float V_Speed,MH_Speed,ML_Speed;
uint8_t R = 1;
uint8_t K = 1;
uint8_t Temp_R = 1;
uint8_t Temp_K = 1;
_Bool sel_index;
uint8_t N;
void LCD_Process(void)
{
	uint8_t lcd_buf[20];	
	if(LCD_Display == 0)
	{
		LCD_DisplayStringLine(Line1,(unsigned char*)"        DATA");
		
		if(PWM_mode == 0)
		{
			sprintf((char *)lcd_buf,"     M=%c",'L');
			LCD_DisplayStringLine(Line3,lcd_buf);
		}
		else
		{
			sprintf((char *)lcd_buf,"     M=%c",'H');
			LCD_DisplayStringLine(Line3,lcd_buf);
		}
		sprintf((char *)lcd_buf,"     P=%2d%%",Pulse);
		LCD_DisplayStringLine(Line4,lcd_buf);
		sprintf((char *)lcd_buf,"     V=%.1f   ",V_Speed);
		LCD_DisplayStringLine(Line5,lcd_buf);
	}
	if(LCD_Display == 1)
	{
		LCD_DisplayStringLine(Line1,(unsigned char*)"        PARA");
		
		sprintf((char *)lcd_buf,"     R=%d  ",Temp_R);
		LCD_DisplayStringLine(Line3,lcd_buf);
		sprintf((char *)lcd_buf,"     K=%d  ",Temp_K);
		LCD_DisplayStringLine(Line4,lcd_buf);	
	}
	if(LCD_Display == 2)
	{
		LCD_DisplayStringLine(Line1,(unsigned char*)"        RECD");
		
		sprintf((char *)lcd_buf,"     N=%d",N);
		LCD_DisplayStringLine(Line3,lcd_buf);
		sprintf((char *)lcd_buf,"     MH=%.1f",MH_Speed);
		LCD_DisplayStringLine(Line4,lcd_buf);
		sprintf((char *)lcd_buf,"     ML=%.1f",ML_Speed);
		LCD_DisplayStringLine(Line5,lcd_buf);		
	}
}

//ADC
float r37_vlot;
uint16_t adc_buf;
void ADC_Process(void)
{
	HAL_ADC_Start(&hadc2);
	adc_buf = HAL_ADC_GetValue(&hadc2);
	r37_vlot = adc_buf / 4095.0f * 3.3f;
	
	if(r37_vlot <= 1.0f)
		Pulse = 10;
	else if(r37_vlot >= 3.0f)
		Pulse = 85;
	else
		Pulse = (uint8_t)(37.5f * r37_vlot - 27.5f);
}

//PWM
_Bool b2_flag;		//0：可切换   1:不切换,正在转换
uint32_t PWM_tick;
void PWM_Process(void)
{
	 if(b2_flag == 1)
	 {
		if(PWM_mode == 0)
		{
			TIM2 -> ARR = (u32)(249.0f - (uwTick - PWM_tick) / 40.0f);
			TIM2 -> CCR2 = (u32)((250.0f - (uwTick - PWM_tick) / 40.0f) * Pulse / 100.0f);
		}
		else
		{
			TIM2 -> ARR = (u32)(124.0f + (uwTick - PWM_tick) / 40.0f);
			TIM2 -> CCR2 = (u32)((125.0f + (uwTick - PWM_tick) / 40.0f) * Pulse / 100.0f);
		}
	 }
	 else
	 {
		 PWM_tick = uwTick;
		if(PWM_mode == 0)
		{
			TIM2 -> ARR = 249;
			TIM2 -> CCR2 = (uint32_t)(250.0f * Pulse / 100.0f);
		}
		else
		{
			TIM2 -> ARR = 124;
			TIM2 -> CCR2 = (uint32_t)(125.0f * Pulse / 100.0f);
		}
	 }
}

//按键
uint32_t key_tick;
uint32_t B2_tick;
uint32_t B4_tick;
uint8_t B4_count;
void Key_Process(void)
{
	if(uwTick - B2_tick >= 5000 && b2_flag == 1)
	{
		PWM_mode = !PWM_mode;	
		b2_flag = 0;
	}	
	if(uwTick - key_tick < 20) return;
	key_tick = uwTick;
	
	Key_Read();
	if(Trg & 0x01)
	{
		LCD_Display = (LCD_Display + 1) % 3;
		LCD_Clear(Black);
		if(LCD_Display == DATA)
			sel_index = 0;
		if(LCD_Display == RECD)
		{
			R = Temp_R;
			K = Temp_K;
		}
	}
	if(Trg & 0x02)
	{
		if(LCD_Display == DATA)
		{
			if(b2_flag == 0)
			{
				B2_tick = uwTick;
				b2_flag = 1;
			}
		}
		else if(LCD_Display == PARA)
		{
			sel_index = !sel_index;
		}
	}
	if(Trg & 0x04)
	{
		if(LCD_Display == PARA) 
		{
			if(sel_index == 0)
				Temp_R = Temp_R % 10 + 1;	
			else
				Temp_K = Temp_K % 10 + 1;
		}
	}
	if(Trg & 0x08)
	{
		if(LCD_Display == PARA)
		{
			if(sel_index == 0)
			{
				Temp_R --;
				if(Temp_R == 0)
					Temp_R = 10;
			}
			else
			{
				Temp_K --;
				if(Temp_K == 0)
					Temp_K = 10;
			}				
		}
	}
	
	if(con & 0x08)
	{
		if(LCD_Display == DATA)
			B4_count++;
	}
	if(Trg == 0x00 && con == 0x00)
	{
		if(B4_count >= 100)
		{
			B4_count = 0;
		}
		else if(B4_count > 0)
		{
			B4_count = 0;
		}
			
	}
}

//输入捕获
volatile _Bool PWM_flag;
uint32_t PWM_tick;
uint16_t PWM_Count;
uint32_t freq;
float V_prev;
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
	PWM_Count = __HAL_TIM_GetCounter(&htim3);
	__HAL_TIM_SetCounter(&htim3,0);
		
	freq = 1000000 / PWM_Count; 
	V_prev = V_Speed;
	V_Speed = freq * 2.0f * 3.14f * R / 100.0f / K;
	if(PWM_mode == 0)
	{
		if(fabs(V_prev - V_Speed) < 2.0f)
		{
			if(V_Speed > ML_Speed)
			{
				if(PWM_flag == 0)
				{
					PWM_flag = 1;
					PWM_tick = uwTick;
				}
				if((uwTick - PWM_tick) >= 2000 && (PWM_flag == 1))
				{
					PWM_flag = 0;
					ML_Speed = V_Speed;
				}
			}
		}
		else
			PWM_flag = 0;
	}
	else
	{
		if(fabs(V_Speed - V_prev) < 2.0f)
		{
			if(V_Speed > MH_Speed)
			{
				if(PWM_flag == 0)
				{
					PWM_tick = uwTick;
					PWM_flag = 1;
				}
				if((uwTick - PWM_tick) >= 2000 && (PWM_flag == 1))
				{
					PWM_flag = 0;
					MH_Speed = V_Speed;
				}
			}
		}
		else
			PWM_flag = 0;
	}
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_ADC2_Init();
  MX_TIM2_Init();
  MX_TIM3_Init();
  /* USER CODE BEGIN 2 */

    LCD_Init();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */

    LCD_Clear(Black);
    LCD_SetBackColor(Black);
    LCD_SetTextColor(White);

	HAL_ADC_Start(&hadc2);
	HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_2);

	HAL_TIM_IC_Start_IT(&htim3,TIM_CHANNEL_2);

    while (1)
    {
    /* USER CODE END WHILE */
		LCD_Process();
		ADC_Process();
		Key_Process();
		PWM_Process();
    /* USER CODE BEGIN 3 */
    }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
  /** Initializes the CPU, AHB and APB busses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2;
  RCC_OscInitStruct.PLL.PLLN = 20;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB busses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the peripherals clocks
  */
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC12;
  PeriphClkInit.Adc12ClockSelection = RCC_ADC12CLKSOURCE_SYSCLK;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
    /* User can add his own implementation to report the file name and line number,
       tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
